//
//  ModifyUserInfoViewModel.swift
//  mmda
//
//  Created by 李陆涛 on 2018/5/26.
//  Copyright © 2018年 mmda. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa

class ModifyUserInfoViewModel: NSObject {
    
    var user = AppManager.share.user
    
    let nickname = Variable("")
    let sex = Variable(Gender.Man)
    let birthday = Variable(Date())
    let email = Variable("")
    let sign = Variable("")
    let showLoading = Variable(false)
    let message = Variable("")
    
    
    var userHasChanged:Observable<Bool>
    
    var loadSuccess:(()->Void)?
    
    override init() {
        
        sex.value = user?.sex ?? .Woman
        birthday.value = user?.birthday ?? Date.init()
        
        userHasChanged = Observable
            .combineLatest(nickname.asObservable(),sex.asObservable(),birthday.asObservable(),email.asObservable(),sign.asObservable()){
                
                nk,sx,by,el,sn in
                
                let user = AppManager.share.user
                
                return nk != user?.nickname || sx != user?.sex || by != user?.birthday || el != user?.email || sn != user?.label
                
            }.share(replay: 1)
    }
    
    
    func commit() {
        
        var params = Dictionary<String, Any>()
        
        
        if nickname.value != user?.nickname {
            params["nickname"] = nickname.value
        }
        
        if sex.value != user?.sex {
            params["sex"] = sex.value.rawValue
        }
        
        if birthday.value != user?.birthday {
            params["birthday"] = birthday.value.timeIntervalSince1970
        }
        if sign.value != user?.label {
            params["label"] = sign.value
        }
        
        if email.value != user?.email {
            params["email"] = email.value
        }

        showLoading.value = true
        NetAPI.changeprofile(params: params).request {
            
            [weak self] response, errmsg in
            guard let `self` = self else { return }
            
            self.showLoading.value = false
            
            guard let err = errmsg else {
                
                self.loadSuccess?()
                self.message.value = "修改成功"
                return
            }
            
            self.message.value = err
        }
    }
    
}



